<template>

  <view class="code-btn" @click="getCode">
    {{time ? time + 's':'发送验证码'}}
  </view>

</template>
<script>
  let timer = null
  export default {
    name: "code-btn",
    
    props: {
      isValid:{
        type:Boolean,
        default:''
      }
      
    },
    data() {
      return {
        time: 0,
        
      };
    },
    
    methods: {
       async getCode() {
       await this.$emit('validate-phone')
        if (!this.isValid) {
            
            return;
          }
        
          // 手机号验证通过，执行获取验证码的逻辑
          if (this.time > 0) return; // 如果倒计时还在进行中，则不执行后续逻辑
          this.time = 10; // 初始化倒计时时间
          
          // 调用发送验证码接口
          const {data:res}=await uni.$http.get('/farmer/sendMsg', this.phone)
          this.$emit('syncCode',res.data)
          uni.showModal({
            title: '验证码',
            content: res.data,
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定');
              } else if (res.cancel) {
                console.log('用户点击取消');
              }
            }
          });
          this.timer = setInterval(() => {
            this.time--;
            if (this.time <= 0) {
              clearInterval(this.timer);
            }
          }, 1000);
        
         
          
          
        


      }



      //   this.$api.getCaptchat({
      //     phone: this.phone
      //   }).then(res => {
      //     //当成功获取验证码时
      //     this.time = 60
      //     this.$toast('验证码:' + res)
      //     //每秒 time--
      //     this.timer = setInterval(() => {
      //       this.time--
      //       if (this.time <= 0) {
      //         clearInterval(this.timer)
      //       }
      //     }, 1000)
      //   }).catch(err => {
      //     //若获取验证码失败
      //     this.$toast(err, '请稍后重试')
      //   })
      // }
    }
  }
</script>
<style lang="scss">
  .code-btn {
    width: 80px;
    color: white;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom-right-radius: 5px;
    border-top-right-radius: 5px;
    background-color: #4CAF50;
  }
</style>